package cn.ahaoweb.drule.core.compile.provide.hepler;

import cn.ahaoweb.drule.core.compile.provide.ObjectTree;
import cn.ahaoweb.drule.core.compile.structure.DruleBlock;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ahao
 * @datetime 2025/6/4 15:16
 * @description 字段匹配信息
 */
@Data
public class MatchedField implements Serializable {

    // 字段
    private ObjectTree.Node field;

    // 匹配信息
    private List<DruleBlockMatcher> matchers;

    // 是否有配对成功
    private Boolean matched;

    public MatchedField(ObjectTree.Node field) {
        this.field = field;
        this.matchers = new ArrayList<>();
        this.matched = false;
    }

    public void add(DruleBlock druleBlock, DruleBlock.Condition condition){
        DruleBlockMatcher m = getDruleBlockMatcher(druleBlock);
        m.getWhenList().add(condition);
    }

    public void addCondition(DruleBlock druleBlock, List<DruleBlock.Condition> conditions){
        DruleBlockMatcher m = getDruleBlockMatcher(druleBlock);
        m.getWhenList().addAll(conditions);
    }

    public void add(DruleBlock druleBlock, DruleBlock.Action action){
        DruleBlockMatcher m = getDruleBlockMatcher(druleBlock);
        m.getThenList().add(action);
    }

    public void addAction(DruleBlock druleBlock, List<DruleBlock.Action> actions){
        DruleBlockMatcher m = getDruleBlockMatcher(druleBlock);
        m.getThenList().addAll(actions);
    }


    /**
     * 根据给定的规则块获取对应的匹配器
     *
     * @param druleBlock 给定的规则块
     * @return 返回对应的匹配器
     */
    private DruleBlockMatcher getDruleBlockMatcher(DruleBlock druleBlock) {
        DruleBlockMatcher m = null;
        for (DruleBlockMatcher matcher : matchers) {
            if (matcher.getRule() == druleBlock
                    || druleBlock.getRuleName().equals(matcher.getRule().getRuleName())){
                m = matcher;
                break;
            }
        }
        if (m == null){
            m = new DruleBlockMatcher(druleBlock);
            matchers.add(m);
        }
        return m;
    }

    @Data
    public static class DruleBlockMatcher implements Serializable{

        // 规则
        private DruleBlock rule;

        // 所匹配的具体条件（Condition）
        private List<DruleBlock.Condition> whenList;

        // 所匹配的具体结果（Action）
        private List<DruleBlock.Action> thenList;

        public DruleBlockMatcher(DruleBlock rule) {
            this.rule = rule;
            this.whenList = new ArrayList<>();
            this.thenList = new ArrayList<>();
        }
    }

}
